package com.wx.core.process.message.event;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.wx.commons.ResultConstant;
import com.wx.core.process.BaseProcess;
import com.wx.core.process.BaseResult;
import com.wx.core.process.MsgXmlUtil;
import com.wx.core.process.ProcessResult;
import com.wx.core.process.WxServiceProcess;
import com.wx.core.vo.MsgNews;
import com.wx.core.vo.MsgRequest;
import com.wx.core.vo.MsgResponseNews;
import com.wx.core.vo.MsgResponseText;
import com.wx.core.vo.MsgText;
import com.wx.entity.WxMulReply;
import com.wx.entity.WxPicReply;
import com.wx.entity.WxTextReply;
import com.wx.flag.KeyWordType;
import com.wx.service.WxMulReplyService;
import com.wx.service.WxPicReplyService;
import com.wx.service.WxTextReplyService;
import com.wx.util.StringUtils;

/**
 * @desc 处理菜单时间
 * @author gavin
 * @date 2015-7-16
 * @version 1.0
 */
public class ClickEventProcess extends BaseProcess {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Resource
	WxTextReplyService wxTextReplyService;
	@Resource
	WxPicReplyService wxPicReplyService;
	@Resource
	WxMulReplyService wxMulReplyService;
	@Resource(name="taskExecutor")
	private ThreadPoolTaskExecutor pooltaskExecutor;

	private boolean isFirstRequset = true;
	
	private String serverAblolutlyPath;

	@Override
	public BaseResult process(HttpServletRequest req,HttpServletResponse res,MsgRequest msgReq){

		ProcessResult result = new ProcessResult();
		String eventKey = msgReq.getEventKey();
		if(StringUtils.isEmpty(eventKey))
			return result;
		
		String[] arr = eventKey.split("_");
		if(arr == null || arr.length == 0)
			return result;
		int msgType = Integer.parseInt(arr[1]);
		
		if(isFirstRequset){
			serverAblolutlyPath = getAbsolutPath(req);
			isFirstRequset = false;
		}
		
		if(KeyWordType.TYPE_TXT.equals(msgType)){
			// 文本回复
			WxTextReply wxTextReply = wxTextReplyService.selectByPrimaryKey(Integer
					.parseInt(arr[0]));
			getTextReply(result,wxTextReply,msgReq);
		} else if(KeyWordType.TYPE_PIC.equals(msgType)){
			// 单图文回复
			WxPicReply wxPicReply = wxPicReplyService.selectByPrimaryKey(Integer.parseInt(arr[0]));
			getPicReply(result,wxPicReply,msgReq);
		} else if(KeyWordType.TYPE_MUL_PIC.equals(msgType)){
			// 多图文回复
			WxMulReply wxMulReply = wxMulReplyService.selectByPrimaryKey(Integer.parseInt(arr[0]));
			getMulPicReply(result,wxMulReply,msgReq);
		} else if(KeyWordType.TYPE_RADIO.equals(msgType)){
			// 音频回复

		}
		return result;
	}
	
	/**
	 * @author: gavin
	 * @date: 2015年7月15日
	 * @Title: getTextReply
	 * @Description: 获取关键词文本回复
	 * @param @param msgRequest
	 * @param @return 设定文件
	 * @return ProcessResult 返回类型
	 * @throws
	 */
	private ProcessResult getTextReply(ProcessResult result,WxTextReply wxTextReply,
			MsgRequest msgReq){

		try{
			// 组装发送消息
			MsgText msgText = new MsgText();
			msgText.setContent(wxTextReply.getContent());
			MsgResponseText msgResponseText = WxServiceProcess.getMsgResponseText(msgReq,msgText);
			String xml = MsgXmlUtil.textToXml(msgResponseText);
			result.setResult(xml);
		} catch (Exception e){
			logger.error(e.getMessage());
			result.setCode(ResultConstant.FAILUER);
			result.setErrmsg(e.getMessage());
		}
		result.setCode(ResultConstant.SUCCESS);
		return result;
	}

	/**
	 * @author: gavin
	 * @date: 2015年7月15日
	 * @Title: getTextReply
	 * @Description: 获取关键词单图文回复
	 * @param @param msgRequest
	 * @param @return 设定文件
	 * @return ProcessResult 返回类型
	 * @throws
	 */
	private ProcessResult getPicReply(ProcessResult result,WxPicReply wxPicReply,
			MsgRequest msgRequest){

		try{
			// 获取关键词信息
			List<WxPicReply> wxPicReplyList = new ArrayList<WxPicReply>();
			wxPicReplyList.add(wxPicReply);
			// 组装发送消息
			if(wxPicReplyList != null && wxPicReplyList.size() > 0){
				String xml = getResponseNews(msgRequest,wxPicReplyList);
				result.setResult(xml);
			}
		} catch (Exception e){
			logger.error(e.getMessage());
			result.setCode(ResultConstant.FAILUER);
			result.setErrmsg(e.getMessage());
		}
		result.setCode(ResultConstant.SUCCESS);
		return result;
	}

	/**
	 * @author: gavin
	 * @date: 2015年7月15日
	 * @Title: getTextReply
	 * @Description: 获取关键词单图文回复
	 * @param @param msgRequest
	 * @param @return 设定文件
	 * @return ProcessResult 返回类型
	 * @throws
	 */
	private ProcessResult getMulPicReply(ProcessResult result,WxMulReply wxMulReply,
			MsgRequest msgRequest){

		try{
			List<WxPicReply> wxPicReplyList = new ArrayList<WxPicReply>();
			String ids = wxMulReply.getPicIds();
			if(StringUtils.isEmpty(ids))
				return null;
			String[] arr = ids.split(",");
			if(arr == null || arr.length == 0)
				return null;
			for(String str:arr){
				if(!StringUtils.isEmpty(str.trim())){
					WxPicReply wxPicReply = wxPicReplyService.selectByPrimaryKey(Integer
							.valueOf(str));
					wxPicReplyList.add(wxPicReply);
				}
			}
			// 组装发送消息
			if(wxPicReplyList != null && wxPicReplyList.size() > 0){
				String xml = getResponseNews(msgRequest,wxPicReplyList);
				result.setResult(xml);
			}
		} catch (Exception e){
			logger.error(e.getMessage());
			result.setCode(ResultConstant.FAILUER);
			result.setErrmsg(e.getMessage());
		}
		result.setCode(ResultConstant.SUCCESS);
		return result;
	}

	/**
	 * @author: gavin
	 * @date: 2015年7月15日
	 * @Title: getResponseNews
	 * @Description: 获取消息
	 * @param @return 设定文件
	 * @return MsgResponseNews 返回类型
	 * @throws
	 */
	private String getResponseNews(MsgRequest msgRequest,List<WxPicReply> wxPicReplyList){

		List<MsgNews> msgNewsList = new ArrayList<MsgNews>();
		wxPicReplyList.forEach(p -> {
			MsgNews msgNews = new MsgNews();
			msgNews.setTitle(p.getTitle());
			msgNews.setPicpath(serverAblolutlyPath+p.getpImgHref());
			msgNews.setUrl(serverAblolutlyPath + "/pic/detail?id=" + p.getId());
			msgNews.setFromurl(p.getArticleUrl());
			msgNews.setBrief(p.getpSummary());
			msgNewsList.add(msgNews);
		});
		MsgResponseNews msgResPonseNews = WxServiceProcess.getMsgResponseNews(msgRequest,
				msgNewsList);
		return MsgXmlUtil.newsToXml(msgResPonseNews);
	}
}
